package com.example.memo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.example.memo.entity.UserInfo;

public class MineFragment extends Fragment implements View.OnClickListener {
    private TextView username,change,help;
    private Button logout;
    private View rootview;
    private UserInfo userInfo;
    private ActivityResultLauncher<Intent> activityResultLauncher;

    public MineFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.fragment_mine, container, false);
        initView(rootview);
        initData();
        return rootview;
    }

    private void initView(View rootview) {
        username = rootview.findViewById(R.id.username);
        change = rootview.findViewById(R.id.change);
        help = rootview.findViewById(R.id.help);
        logout = rootview.findViewById(R.id.logout);

        activityResultLauncher = this.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                o -> {
                    if(o.getResultCode() == 1){
                        startActivity(new Intent(getActivity(),Login.class));
                        getActivity().finish();
                    }
                });

        change.setOnClickListener(this);
        help.setOnClickListener(this);
        logout.setOnClickListener(this);
    }

    private void initData() {
        userInfo = UserInfo.getUserInfo();
        username.setText(userInfo.getAccount());
    }

    @Override
    public void onClick(View view) {
        if(view == change){
            activityResultLauncher.launch(new Intent(getActivity(),changePW.class));
        }else if (view == help) {
            startActivity(new Intent(getActivity(),Help.class));
        }else if (view == logout) {
            new AlertDialog.Builder(getActivity())
                    .setTitle("你确定要退出登陆吗？")
                    .setNegativeButton("取消", (dialogInterface, i) -> {

                    })
                    .setPositiveButton("确定", (dialogInterface, i) -> {
                        startActivity(new Intent(getActivity(),Login.class));
                        getActivity().finish();
                    })
                    .show();
        }
    }
}